<template>
  <div class="dashboard-container">
    <div v-loading="loading">
      <!-- 顶部卡片统计 -->
      <el-row :gutter="20" class="dashboard-header">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-header">
              <span class="label">今日热量</span>
              <el-icon class="icon"><Histogram /></el-icon>
            </div>
            <div class="stat-content">
              <div class="main-value">
                {{ dailyNutrition.calories || 0 }}
                <span class="unit">kcal</span>
              </div>
              <div class="sub-value" :class="getValueClass(dailyNutrition.caloriesProgress)">
                {{ formatProgress(dailyNutrition.caloriesProgress) }}
              </div>
            </div>
            <el-progress 
              :percentage="Math.min(dailyNutrition.caloriesProgress || 0, 100)"
              :color="getProgressColor(dailyNutrition.caloriesProgress)"
            />
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-header">
              <span class="label">蛋白质</span>
              <el-icon class="icon"><Chicken /></el-icon>
            </div>
            <div class="stat-content">
              <div class="main-value">
                {{ dailyNutrition.protein }}
                <span class="unit">g</span>
              </div>
              <div class="sub-value" :class="getValueClass(dailyNutrition.proteinProgress)">
                {{ formatProgress(dailyNutrition.proteinProgress) }}
              </div>
            </div>
            <el-progress 
              :percentage="Math.min(dailyNutrition.proteinProgress, 100)"
              :color="getProgressColor(dailyNutrition.proteinProgress)"
            />
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-header">
              <span class="label">碳水化合物</span>
              <el-icon class="icon"><Bowl /></el-icon>
            </div>
            <div class="stat-content">
              <div class="main-value">
                {{ dailyNutrition.carbs }}
                <span class="unit">g</span>
              </div>
              <div class="sub-value" :class="getValueClass(dailyNutrition.carbsProgress)">
                {{ formatProgress(dailyNutrition.carbsProgress) }}
              </div>
            </div>
            <el-progress 
              :percentage="Math.min(dailyNutrition.carbsProgress, 100)"
              :color="getProgressColor(dailyNutrition.carbsProgress)"
            />
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-header">
              <span class="label">脂肪</span>
              <el-icon class="icon"><KnifeFork /></el-icon>
            </div>
            <div class="stat-content">
              <div class="main-value">
                {{ dailyNutrition.fat }}
                <span class="unit">g</span>
              </div>
              <div class="sub-value" :class="getValueClass(dailyNutrition.fatProgress)">
                {{ formatProgress(dailyNutrition.fatProgress) }}
              </div>
            </div>
            <el-progress 
              :percentage="Math.min(dailyNutrition.fatProgress, 100)"
              :color="getProgressColor(dailyNutrition.fatProgress)"
            />
          </el-card>
        </el-col>
      </el-row>

      <!-- 主要内容区域 -->
      <el-row :gutter="20" class="dashboard-main">
        <!-- 左侧图表区域 -->
        <el-col :xs="24" :md="16">
          <!-- 体重趋势图 -->
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>体重变化趋势</span>
                <el-radio-group v-model="weightRange" size="small" @change="handleWeightRangeChange">
                  <el-radio-button :value="'week'">近7天</el-radio-button>
                  <el-radio-button :value="'month'">近30天</el-radio-button>
                  <el-radio-button :value="'year'">近一年</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="weightChartRef" class="chart-container"></div>
          </el-card>

          <!-- 营养摄入分析 -->
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>营养摄入分析</span>
                <el-date-picker
                  v-model="nutritionDate"
                  type="date"
                  placeholder="选择日期"
                  :disabled-date="disabledDate"
                  @change="handleDateChange"
                  size="small"
                />
              </div>
            </template>
            <div ref="nutritionChartRef" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 右侧信息区域 -->
        <el-col :xs="24" :md="8">
          <!-- 目标进度卡片 -->
          <el-card class="goal-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>目标进度</span>
              </div>
            </template>
            <div class="goal-content">
              <div class="goal-info">
                <div class="goal-type">{{ goalProgress.type || '未设置目标' }}</div>
                <div class="goal-target">目标: {{ goalProgress.target || '-' }}</div>
                <div class="goal-current">当前: {{ goalProgress.current || '-' }}</div>
              </div>
              <el-progress
                type="circle"
                :status="goalProgress.status"
                :percentage="goalProgress.percentage || 0"
              >
                <template #default="{ percentage }">
                  <span class="progress-value">{{ percentage }}%</span>
                  <span class="progress-label">{{ goalProgress.statusText || '进行中' }}</span>
                </template>
              </el-progress>
            </div>
          </el-card>

          <!-- 最近膳食记录 -->
          <el-card class="meal-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>今日膳食记录</span>
                <el-button type="primary" link @click="$router.push('/meal-record')">
                  查看更多
                </el-button>
              </div>
            </template>
            
            <div v-if="recentMeals.length" class="meal-list">
              <div v-for="meal in recentMeals" :key="meal.id" class="meal-item">
                <div class="meal-header">
                  <h4>{{ getMealTypeText(meal.type) }}</h4>
                  <span>{{ meal.time }}</span>
                </div>
                <div class="meal-content">
                  <div class="food-name">{{ meal.description }}</div>
                  <div class="meal-nutrition">
                    <el-tag size="small">{{ meal.calories }}kcal</el-tag>
                    <el-tag size="small" type="success">蛋白质{{ meal.protein }}g</el-tag>
                    <el-tag size="small" type="warning">碳水{{ meal.carbs }}g</el-tag>
                    <el-tag size="small" type="danger">脂肪{{ meal.fat }}g</el-tag>
                  </div>
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无记录" />
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HomePage'
}
</script>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import * as echarts from 'echarts'
import { 
  Histogram, 
  Chicken, 
  Bowl, 
  KnifeFork 
} from '@element-plus/icons-vue'
import { formatDate } from '@/utils/date'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const store = useStore()
const router = useRouter()
const weightChartRef = ref(null)
const nutritionChartRef = ref(null)
let weightChart = null
let nutritionChart = null
const loading = ref(false)

// 日期和范围选择
const nutritionDate = ref(new Date())
const weightRange = ref('week')

// 从 store 获取数据，添加默认值
const dailyNutrition = computed(() => {
  const data = store.state.dashboard.dailyNutrition
  console.log('Daily Nutrition Data:', data)
  return {
    calories: data?.calories ?? 0,
    caloriesProgress: data?.caloriesProgress ?? 0,
    protein: data?.protein ?? 0,
    proteinProgress: data?.proteinProgress ?? 0,
    carbs: data?.carbs ?? 0,
    carbsProgress: data?.carbsProgress ?? 0,
    fat: data?.fat ?? 0,
    fatProgress: data?.fatProgress ?? 0
  }
})

const goalProgress = computed(() => {
  const data = store.state.dashboard.goalProgress
  console.log('Goal Progress Data:', data)
  return {
    type: data?.type ?? '未设置目标',
    target: data?.target ?? '-',
    current: data?.current ?? '-',
    percentage: data?.percentage ?? 0,
    status: data?.status ?? '',
    statusText: data?.statusText ?? ''
  }
})

const recentMeals = computed(() => {
  const data = store.state.dashboard.recentMeals
  console.log('Recent Meals Data:', data)
  return Array.isArray(data) ? data : []
})

const weightTrend = computed(() => {
  const data = store.state.dashboard.weightTrend
  console.log('Weight Trend Data:', data)
  return Array.isArray(data) ? data : []
})

// 格式化进度显示
const formatProgress = (progress) => {
  if (!progress && progress !== 0) return '0%'
  return `${Math.min(progress, 100)}%`
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (!percentage) return '#F56C6C'
  if (percentage < 80) return '#F56C6C'
  if (percentage < 100) return '#E6A23C'
  return '#67C23A'
}

// 获取值的样式类
const getValueClass = (progress) => {
  if (!progress && progress !== 0) return ''
  if (progress >= 100) return 'text-success'
  if (progress >= 80) return 'text-warning'
  return 'text-danger'
}

// 获取膳食类型文本
const getMealTypeText = (type) => {
  const typeMap = {
    breakfast: '早餐',
    lunch: '午餐',
    dinner: '晚餐',
    snack: '加餐'
  }
  return typeMap[type] || type
}

// 日期限制
const disabledDate = (time) => {
  return time.getTime() > Date.now()
}

// 初始化图表
const initCharts = () => {
  if (weightChartRef.value) {
    weightChart = echarts.init(weightChartRef.value)
    // 初始化体重趋势图配置
    const weightOption = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>{a}: {c}kg'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: [],
        axisLabel: {
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '体重(kg)',
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      series: [
        {
          name: '体重',
          type: 'line',
          smooth: true,
          data: [],
          symbolSize: 8,
          itemStyle: {
            color: '#409EFF'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64,158,255,0.3)' },
              { offset: 1, color: 'rgba(64,158,255,0.1)' }
            ])
          }
        }
      ]
    }
    weightChart.setOption(weightOption)
  }

  if (nutritionChartRef.value) {
    nutritionChart = echarts.init(nutritionChartRef.value)
    // 初始化营养摄入分析图配置
    const nutritionOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c}g ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        padding: [20, 0, 0, 0]
      },
      series: [
        {
          name: '营养摄入',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { 
              value: 0, 
              name: '蛋白质',
              itemStyle: { color: '#67C23A' }
            },
            { 
              value: 0, 
              name: '碳水化合物',
              itemStyle: { color: '#E6A23C' }
            },
            { 
              value: 0, 
              name: '脂肪',
              itemStyle: { color: '#F56C6C' }
            }
          ]
        }
      ]
    }
    nutritionChart.setOption(nutritionOption)
  }
}

// 更新图表数据
const updateCharts = () => {
  if (weightChart && weightTrend.value?.length) {
    weightChart.setOption({
      xAxis: {
        data: weightTrend.value.map(item => formatDate(item.date))
      },
      series: [{
        data: weightTrend.value.map(item => item.weight)
      }]
    })
  }

  if (nutritionChart) {
    nutritionChart.setOption({
      series: [{
        data: [
          { 
            value: dailyNutrition.value.protein || 0, 
            name: '蛋白质',
            itemStyle: { color: '#67C23A' }
          },
          { 
            value: dailyNutrition.value.carbs || 0, 
            name: '碳水化合物',
            itemStyle: { color: '#E6A23C' }
          },
          { 
            value: dailyNutrition.value.fat || 0, 
            name: '脂肪',
            itemStyle: { color: '#F56C6C' }
          }
        ]
      }]
    })
  }
}

// 生命周期钩子
onMounted(async () => {
  try {
    loading.value = true
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('用户信息不存在，请重新登录')
      router.push('/login')
      return
    }

    console.log('Mounting HomePage, userId:', userId)
    // 获取仪表盘数据
    const dashboardData = await store.dispatch('dashboard/getDashboardData')
    console.log('Dashboard Data:', dashboardData)
    
    // 等待数据加载完成后再初始化图表
    await nextTick()
    // 先初始化图表
    initCharts()
    // 等待一帧确保图表容器已渲染
    await nextTick()
    // 再更新数据
    updateCharts()
    
    window.addEventListener('resize', handleResize)
  } catch (error) {
    console.error('初始化仪表盘失败:', error)
    ElMessage.error(error.message || '获取数据失败')
  } finally {
    loading.value = false
  }
})

// 处理体重范围变化
const handleWeightRangeChange = async (range) => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('用户信息不存在，请重新登录')
      router.push('/login')
      return
    }

    await store.dispatch('dashboard/getWeightTrend', { range })
    updateCharts()
  } catch (error) {
    console.error('获取体重趋势失败:', error)
    ElMessage.error(error.message || '获取体重趋势失败')
  }
}

// 处理日期变化
const handleDateChange = async (date) => {
  try {
    const userId = localStorage.getItem('userId')
    if (!userId) {
      ElMessage.error('用户信息不存在，请重新登录')
      router.push('/login')
      return
    }

    await store.dispatch('dashboard/getDailyNutrition', date)
    updateCharts()
  } catch (error) {
    console.error('获取营养数据失败:', error)
    ElMessage.error(error.message || '获取营养数据失败')
  }
}

// 监听窗口大小变化
const handleResize = () => {
  weightChart?.resize()
  nutritionChart?.resize()
}

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  weightChart?.dispose()
  nutritionChart?.dispose()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;

  .dashboard-header {
    margin-bottom: 20px;

    .stat-card {
      .stat-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .label {
          font-size: 16px;
          color: var(--el-text-color-regular);
        }

        .icon {
          font-size: 24px;
          color: var(--el-color-primary);
        }
      }

      .stat-content {
        margin-bottom: 16px;

        .main-value {
          font-size: 24px;
          font-weight: bold;
          color: var(--el-text-color-primary);

          .unit {
            font-size: 14px;
            color: var(--el-text-color-secondary);
            margin-left: 4px;
          }
        }

        .sub-value {
          font-size: 14px;
          margin-top: 4px;

          &.text-success {
            color: var(--el-color-success);
          }

          &.text-warning {
            color: var(--el-color-warning);
          }

          &.text-danger {
            color: var(--el-color-danger);
          }
        }
      }
    }
  }

  .dashboard-main {
    .chart-card {
      margin-bottom: 20px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart-container {
        height: 300px;
      }
    }

    .goal-card {
      margin-bottom: 20px;

      .goal-content {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .goal-info {
          .goal-type {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 8px;
          }

          .goal-target,
          .goal-current {
            color: var(--el-text-color-secondary);
            margin-bottom: 4px;
          }
        }

        .progress-value {
          font-size: 20px;
          font-weight: bold;
          display: block;
        }

        .progress-label {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }
    }

    .meal-card {
      .meal-nutrition {
        margin-top: 8px;

        .el-tag {
          margin-right: 8px;
        }
      }

      .empty-state {
        padding: 40px 0;
      }
    }
  }

  // 添加 loading 样式
  .el-loading-mask {
    background-color: rgba(255, 255, 255, 0.8);
  }
}
</style> 